package com.situ.player.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.situ.player.R;
import com.situ.player.adapter.FileAdapter;

import java.io.File;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    private ListView listView;
    // 当前正在展示的文件的目录,初始是sd卡的根目录
    private File currentDirectoryFile;
    private FileAdapter fileAdapter;

    // 存放所有的权限
    private ArrayList<String> permissionList = new ArrayList<String>();
    // 需要申请权限
    private ArrayList<String> askPermissionList = new ArrayList<String>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = findViewById(R.id.list_view);

        permissionList.add(Manifest.permission.READ_EXTERNAL_STORAGE);
        permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);

        checkPermission(permissionList, askPermissionList);
        if (askPermissionList.size() > 0) {// 有需要申请的权限
            requestPermissions(askPermissionList, 1);
        } else {
            // 对于低版本安卓手机或者高版本已经用户已经授权了权限的，直接执行这里
            currentDirectoryFile = getSDPath();
            fileAdapter = new FileAdapter(this);
            fileAdapter.updateData(currentDirectoryFile);
            listView.setAdapter(fileAdapter);
        }
    }

    /***
     * 请求权限的方法，requestPermissions() 传入一个Activity，一个需要的权限的数组，
     * 和一个整形的request code，与用户完成交互后，系统会回调该方法并返回对用的request code
     * @param needAskPermisson
     * @param requestCode
     */
    private void requestPermissions(ArrayList<String> needAskPermisson, int requestCode) {
        String[] needpermisson = new String[needAskPermisson.size()];
        needpermisson = needAskPermisson.toArray(needpermisson);
        ActivityCompat.requestPermissions(this, needpermisson, 1);//弹出对话框
    }

    /****
     * 判断应用权限的有无，如果没有这项权限，则将权限加入到askPermissionsList
     * @param permissionList
     * @param askpermissionsList
     */
    private void checkPermission(ArrayList<String> permissionList, ArrayList<String> askpermissionsList) {
        for (int i = 0; i < permissionList.size(); i++) {
            //检查权限的方法，第一个参数是context，第二个参数是权限名，返回值为PERMISSION_GRANTED（有权限）和PERMISSION_DENIED(无权限）
            if (ContextCompat.checkSelfPermission(this, permissionList.get(i)) != PackageManager.PERMISSION_GRANTED) {
                askpermissionsList.add(permissionList.get(i));
            }
        }
    }


    // 返回用户在申请权限框选择的结果
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (verifyPermisson(grantResults)) {// 用户允许了这个权限
            // 首先获得sdcard的根目录
            currentDirectoryFile = getSDPath();
            fileAdapter = new FileAdapter(this);
            fileAdapter.updateData(currentDirectoryFile);
            listView.setAdapter(fileAdapter);
        } else {
            finish();
        }
    }

    // 返回sdcard的根目录
    private File getSDPath() {
        File sdCard = null;
        boolean isSDCardExist = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
        if (isSDCardExist) {
            sdCard = Environment.getExternalStorageDirectory();
        } else {
            sdCard = Environment.getRootDirectory();
        }
        return  sdCard;
    }

    // 在确认框里面验证用户到底允不允许这个权限
    private boolean verifyPermisson(int[] grantResults) {
        if (grantResults.length < 1) {
            return false;
        }
        for (int result : grantResults) {
            if (result != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // 只处理back按键
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            // 不是sd卡根目录，可以不停的back
            if (!currentDirectoryFile.equals(Environment.getExternalStorageDirectory())) {
                // 返回上一层目录
                String parentPath = currentDirectoryFile.getParent();
                currentDirectoryFile = new File(parentPath);
                // 更新Adapter里面的数据
                fileAdapter.updateData(currentDirectoryFile);
            } else {// 是sd卡根目录，直接finish
                finish();
            }


            // 我们自己已经处理了back按键的操作
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    public void updatePath(File file) {
        currentDirectoryFile = file;
    }
}